/*   Copyright (C) 2008  Jeroen v. Schagen & Youri Lima
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Text;
using System.Net.Sockets;
using System.Collections;

using Engine.Connection.Server;
using Engine.Connection.Util;

namespace ChatServer
{
    // Chat server
    class ChatServer : SocketServer
    {
        // Singleton instance
        private static ChatServer instance;

        // Overloaded constructor
        private ChatServer() : base("Chat")
        {
            
        }

        // String specified Send
        public void Send(string message)
        {
            // Encode message
            byte[] data = Encoding.ASCII.GetBytes(message);

            // Send
            Send(data);
        }

        public void Send(string message, SocketUser client)
        {
            // Encode message
            byte[] data = Encoding.ASCII.GetBytes(message);

            // Send
            Send(data, client);
        }

        // Connect callback
        protected override void OnClientConnect(IAsyncResult asyn)
        {
            SocketUser client = new SocketUser();

            try
            {
                // Retrieve client
                client.Socket = socket.EndAccept(asyn);

                client.Object = "Client #" + (clients.Count + 1);

                // Save socket
                clients.Add(client);

                // Let client wait for data
                WaitForData(client);

                // Send message
                Send(client.Object + " has joined the server!");

                // Free callback
                socket.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }

            // Server was shut down
            catch (ObjectDisposedException)
            {
                // Correct collection
                clients.Remove(client);
            }
        }

        // Data callback
        protected override void OnDataReceived(IAsyncResult asyn)
        {
            SocketPackage packet = null;

            try
            {
                // Initiate packet
                packet = (SocketPackage) asyn.AsyncState;

                // End asynchronous read
                int length = packet.User.Socket.EndReceive(asyn);

                // Decode packet
                Decoder d = Encoding.ASCII.GetDecoder();

                // Retrieve package
                char[] chars = new char[length];
                d.GetChars(packet.DataBuffer, 0, length, chars, 0);

                // Enqueue package
                packages.Enqueue(packet);

                // Wait for next packet
                WaitForData(packet.User);
            }

            // Connection to client lost
            catch (SocketException)
            {
                // Correct collection
                clients.Remove(packet.User);

                // Send message
                Send(packet.User.Object + " has left the server!");
            }
        }

        // Singleton instance
        public static ChatServer Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ChatServer();
                }

                return instance;
            }
        }
    }
}
